package com.pss.back.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.pss.back.interceptor.model.User;
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;

/**
 * @创建人 czj
 * @创建时间 2021/9/15
 * @描述
 */
public class JWTUtils {

    private static final String SIGN = "231@$#!$@";//秘钥

    //生成token
    public static String getToken(User user){
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("username",user.getUsername());
        builder.withClaim("userID",user.getId());

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,1);//token过期时间,7天

        String token = builder.withExpiresAt(calendar.getTime())//设置token过期时间
                .sign(Algorithm.HMAC512(user.getPassword()));//使用秘钥进行加密

        return token;
    }

    //验证token，验证不成功会抛出异常
    public static boolean verifierToken(User user, String token){
//        String token1 = getToken(user);
        //验证过期时间
        Date expiresAt = JWT.decode(token).getExpiresAt();
        if (new Date().getTime() > expiresAt.getTime()) {
            return false;
        }
        if (!StringUtils.equals(user.getPassword(),token)) {
            return false;
        }
        return true;
//        JWT.require(Algorithm.HMAC512(user.getPassword())).build().verify(token);
    }


    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJleHAiOjE2MzIyOTY2MDYsInVzZXJJRCI6IjEiLCJ1c2VybmFtZSI6IjEifQ.dil3F66yHCSS7BlPccWPMgh-B2Kh9DE1sSfnPsMF6MM8Lzj2ec2_MqI4BsaHXpPuiK9ssDuH8gd8OgsEtrf64g";

    }
}
